package validate

import (
	"context"
	"gitee.com/bobo-rs/idea-space-framework/pkg/ifile"
	"gitee.com/bobo-rs/idea-space-framework/pkg/img"
	"github.com/gogf/gf/v2/errors/gerror"
	"github.com/gogf/gf/v2/util/gvalid"
	"regexp"
)

// RuleRegisterDesign 注册设计规则
func RuleRegisterDesign() {
	gvalid.RegisterRuleByMap(map[string]gvalid.RuleFunc{
		`selling-match`:        RuleSellingMatch,
		`base64-prefix-match`:  RuleBase64PrefixMatch,
		`base64-content-match`: RuleBase64ContentMatch,
		`template-id-exists`:   RuleMaterialTemplateExistsById,
	})
}

// RuleSellingMatch 卖点词匹配
func RuleSellingMatch(ctx context.Context, in gvalid.RuleFuncInput) error {
	var (
		selling = in.Value.String()
	)
	if len(selling) == 0 {
		return gerror.New(`缺少卖点词`)
	}
	// 因GO不支持负向前瞻 (?!...) 拆分验证^[^\s,，]
	if !regexp.MustCompile(`^[^\s,，]`).MatchString(selling) {
		return gerror.New(`卖点开头不能存在空格和中英文逗号`)
	}
	// 正则匹配规则
	re := regexp.MustCompile(`^[\x{4e00}-\x{9fa5}0-9a-zA-Z\s,，]*$`)
	if !re.MatchString(selling) {
		return gerror.New(`卖点格式只能支持中文、英文和数字开头，且支持空格，并通过中英文逗号分割卖点`)
	}
	return nil
}

// RuleBase64PrefixMatch 验证图片base64前缀格式
func RuleBase64PrefixMatch(ctx context.Context, in gvalid.RuleFuncInput) error {
	_, err := ifile.ParseBase64ImageExt(in.Value.String())
	return err
}

// RuleBase64ContentMatch 验证转base64后图片内容是否有效
func RuleBase64ContentMatch(ctx context.Context, in gvalid.RuleFuncInput) error {
	_, err := img.ParseContentToImage(in.Value.String())
	return err
}
